package com.zhongke.cotrun.service.impl;

import com.zhongke.cotrun.mapper.RegionMapper;
import com.zhongke.cotrun.model.pojo.Region;
import com.zhongke.cotrun.service.RegionService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 作者 yhl
 * 日期 2020-01-05 03:06:00
 * 描述 Region 服务实现
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class RegionImpl implements RegionService {
    @Resource
    private RegionMapper regionMapper;


    @Override
    public Region queryByRegionId(int regionId) {

        if (regionId <= 0) {
            return null;
        }
        return getRegionFromRedis(regionId);
    }

    @Override
    @Cacheable(cacheNames = "sysConfig:region",key = "#regionId")
    public List<Region> listAllChildrenRegion(int regionId) {
        if (regionId <= 0) {
            return null;
        }
        return getAllChildrenRegionFromRedis(regionId);
    }

    /**
     * 根据主键删除数据
     *
     * @param projectId
     */
    @Override
    public int deleteByPrimaryKey(Integer projectId) {
        return regionMapper.deleteByPrimaryKey(projectId);
    }

    /**
     * 插入数据库记录
     *
     * @param record
     */
    @Override
    public int insertSelective(Region record) {
        return regionMapper.insertSelective(record);
    }

    /**
     * 修改数据
     *
     * @param record
     */
    @Override
    public int updateByPrimaryKeySelective(Region record) {
        return regionMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 根据主键id查询
     *
     * @param projectId
     */
    @Override
    public Region selectByPrimaryKey(Integer projectId) {
        return regionMapper.selectByPrimaryKey(projectId);
    }

    private List<Region> getAllChildrenRegionFromRedis(Integer parentId) {
        if (null == parentId || parentId <= 0) {
            return null;
        }
        return regionMapper.listAllChildrenRegion(parentId);
    }

    private Region getRegionFromRedis(Integer regionId) {
        if (null == regionId || regionId <= 0) {
            return null;
        }

        return regionMapper.queryByRegionId(regionId);
    }
}
